package v1

import (
	"github.com/gin-gonic/gin"
	"hytx_media/pkg/app"
	"github.com/astaxie/beego/validation"
	"net/http"
	"hytx_media/service/sms_service"
	"hytx_media/models"
	"hytx_media/pkg/util"
	"golang.org/x/crypto/bcrypt"
)


// 修改密码
func ModifyPassword(c *gin.Context)  {
	appG := app.Gin{c}

	code := c.PostForm("code")
	password := c.PostForm("password")
	repeat_password := c.PostForm("repeat_password")


	valid := validation.Validation{}
	valid.Required(code, "title").Message("验证码不能为空！")
	valid.Required(password, "password").Message("密码码不能为空！")
	valid.Required(repeat_password, "repeat_password").Message("密码码不能为空！")

	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.ResponseMsg(http.StatusOK, "false", valid.Errors)
		return
	}

	if password != repeat_password {
		appG.ResponseMsg(http.StatusOK, "false", "两次密码不相等")
		return
	}

	user := c.MustGet("user").(*models.MediaUser)

	// 短信验证
	sms_service := sms_service.SMSValidate{MobilePhone:user.Phone, MsgCode:code}
	isCheck, _ :=sms_service.Check()

	if !isCheck {
		appG.ResponseMsg(http.StatusOK, "false", "短信验证失败")
		return
	}

	md5password := util.EncodeMD5(password)

	// 修改密码
	if err := models.DB.Model(&models.MediaUser{}).Where("id = ?", user.ID).Update("password", md5password).Error; err != nil{
		appG.ResponseMsg(http.StatusOK, "false", "数据库操作失败")
		return
	}

	appG.ResponseMsg(http.StatusOK, "true", nil)
}

// 重置密码
func ResetPassword(c *gin.Context)  {
	appG := app.Gin{c}

	code := c.PostForm("code")
	phone := c.PostForm("phone")
	password := c.PostForm("password")
	repeat_password := c.PostForm("repeat_password")


	valid := validation.Validation{}
	valid.Required(code, "title").Message("验证码不能为空！")
	valid.Required(password, "password").Message("密码码不能为空！")
	valid.Required(repeat_password, "repeat_password").Message("密码码不能为空！")

	if valid.HasErrors() {
		//app.MarkErrors(valid.Errors)
		appG.ResponseMsg(http.StatusOK, "账号信息错误", false)
		return
	}

	if password != repeat_password {
		appG.ResponseMsg(http.StatusOK, "两次密码不相等", false)
		return
	}

	// 短信验证
	sms_service := sms_service.SMSValidate{MobilePhone:phone, MsgCode:code}
	isCheck, _ :=sms_service.Check()

	if !isCheck {
		appG.ResponseMsg(http.StatusOK, "短信验证失败", false)
		return
	}

	md5password,_ := bcrypt.GenerateFromPassword([]byte(password), 10)

	// 修改密码
	if err := models.DB.Model(&models.MediaUser{}).Where("phone = ?", phone).Update("password", md5password).Error; err != nil{
		appG.ResponseMsg(http.StatusOK, "数据库操作失败", false)
		return
	}

	appG.ResponseMsg(http.StatusOK, "ok", true)
}